<template>
    <el-button type="primary" @click="AddDatasave">+ 新增</el-button>
    <el-button type="primary" :icon="Delete"> 删除</el-button>
    <div style="border: 1px solid black; padding: 10px; margin: 10px;">
        <el-table :data="tableData" border style="width: 100%">

            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="60" />

            <el-table-column prop="goodsName" label="商品名称" width="90" align="center" />
            <el-table-column prop="goodsBatch" label="生成批次" width="90" align="center" />
            <el-table-column prop="goodsExpiration" label="保质期(天)" width="100" align="center" />
            <el-table-column prop="goodsLicense" label="生成许可证号" width="140" align="center" />
            <el-table-column prop="goodsEnterprise" label="生成企业" width="130" />
            <el-table-column prop="createTime" label="创建时间" width="180">
                <template #default="script">
                    {{ moment(script.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" min-width="200">
                <template #default="script">
                    <el-button link type="primary" size="small" @click="detail(script.row.id)">
                        详情
                    </el-button>
                    <el-button link type="primary" size="small">修改</el-button>
                    <el-button link type="primary" size="small" >
                        导出溯源码
                    </el-button>
                    <el-button link type="primary" size="small" @click="DelateData(script.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="Page.PageIndex" v-model:page-size="Page.PageSize"
            :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="Page.TotalCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    </div>

    <!-- 添加商品基本信息的弹框 -->
    <el-dialog v-model="dialogFormVisible" title="基本信息(添加)" width="500">

        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">

            <el-form-item label="商品名称" prop="goodsId">
                <el-select v-model="ruleForm.goodsId" placeholder="请选择">
                    <el-option v-for="value in Show" :label="value.goodsName" :value="value.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="生成批次" prop="goodsBatch">
                <el-input v-model="ruleForm.goodsBatch" />
            </el-form-item>

            <el-form-item label="保质期(天)" prop="goodsExpiration">
                <el-input v-model="ruleForm.goodsExpiration" />
            </el-form-item>


            <el-form-item label="生成许可证号" prop="goodsLicense">
                <el-input v-model="ruleForm.goodsLicense" />
            </el-form-item>

            <el-form-item label="生成企业" prop="goodsEnterprise">
                <el-input v-model="ruleForm.goodsEnterprise" />
            </el-form-item>

            <el-form-item label="封面图" prop="goodsPhoto">

                <el-upload class="avatar-uploader" action="http://localhost:5002/api/Upload/FileUpload"
                    :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="ruleForm.goodsPhoto" :src="ruleForm.goodsPhoto" class="avatar"
                        style="width: 178px; right: 178px;" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>

            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    添加
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>


</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios'
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
} from '@element-plus/icons-vue'
import moment from 'moment'
import type { FormInstance, FormRules } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { fa } from 'element-plus/es/locales.mjs'
import router from '@/router'



interface RuleForm {
    goodsId: any
    goodsBatch: string
    goodsExpiration: any
    goodsLicense: string
    goodsEnterprise: string
    goodsPhoto: string
    createPeop: any
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    goodsId: '',
    goodsBatch: '',
    goodsExpiration: 0,
    goodsLicense: '',
    goodsEnterprise: '',
    goodsPhoto: '',
    createPeop: ''
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RuleForm>>({
    goodsId: [
        { required: true, message: '请选择商品', trigger: 'blur' },
    ],
    goodsBatch: [
        { required: true, message: '生成批次不能为空', trigger: 'change' },
        { max: 30, message: '生产批次最多支持输入30个字符', trigger: 'blur' },
    ],
    goodsExpiration: [
        { required: true, message: '保质期不能为空', trigger: 'change' },
        // { type: 'number', message: '只能输入数字', trigger: 'change' },
        { max: 5, message: '保质期最多支持输入5个字符', trigger: 'blur' },
    ],
    goodsLicense: [
        { required: true, message: '生产许可证号不能为空', trigger: 'change' },
        { max: 30, message: '生产许可证号最多支持输入30个字符', trigger: 'blur' },
    ],
    goodsEnterprise: [
        { required: true, message: '生产企业不能为空', trigger: 'change' },
        { max: 30, message: '生产企业最多支持输入30个字符', trigger: 'blur' },
    ],
    goodsPhoto: [
        { required: true, message: '封面图不能为空', trigger: 'change' },
    ],
})


// 
// 商品信息的下拉框 商品基本信息的显示 分页方法 
const tableData = ref([])
const Page = reactive({
    PageIndex: 1,
    PageSize: 10,
    TotalCount: 0,
    TatalPage: 0

})
const Show = <any>ref([])
const GoodsShow = () => {
    axios.get("http://localhost:5002/api/Goods/GoodsShow").then(res => {
        Show.value = res.data.data
        console.log(Show.value)
    })
}
const BasicinfoShow = () => {
    axios.get("http://localhost:5002/api/Goods/BasicinfoShow", {
        params: {
            PageIndex: Page.PageIndex,
            PageSize: Page.PageSize
        }
    }
    ).then(res => {
        console.log(res.data.iteims)
        tableData.value = res.data.iteims
        Page.TotalCount = res.data.totalCount
        Page.TatalPage = res.data.totalPage
    })
}

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    Page.PageSize = val
    BasicinfoShow()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    Page.PageIndex = val
    BasicinfoShow()
}


//添加弹框的显示 
const dialogFormVisible = ref(false)
const AddDatasave = () => {
    //alert("iadsjaesjolikd");
    dialogFormVisible.value = true;
}

//图片上传
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,) => {
    ruleForm.goodsPhoto = "http://localhost:5002/" + response
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片格式必须是JPG!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('上传的图片不能超过2MB!')
        return false
    }
    return true
}

//添加商品基本信息
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            //console.log("asdasdsa", ruleForm.goodsPhoto);
            // alert(ruleForm.goodsPhoto)
            // alert(ruleForm.createPeop)
            ruleForm.createPeop = localStorage.getItem("userReal")
            axios.post("http://localhost:5002/api/Goods/BasicinfoAdd", ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("添加成功");
                    dialogFormVisible.value = false;
                    BasicinfoShow();
                }
                else {
                    ElMessage.success("添加失败");
                    dialogFormVisible.value = false;
                    BasicinfoShow();
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

//跳转详情页面
const detail = (id: any) => {
    //alert("asdsadsadasdadsad");
    //alert(id);
    router.push({ path: "/detail", query: { id } })
}

//删除
const DelateData = (id: any) => {
    ElMessageBox.confirm(
        '您确定要删除吗?',
        '删除警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // ElMessage({
            //     type: 'success',
            //     message: 'Delete completed',
            // })

            axios.put("http://localhost:5002/api/Goods/BasicinfoDel", { id: id }).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("删除成功")
                    BasicinfoShow()
                }
                else {
                    ElMessage.error("删除失败")
                    BasicinfoShow()
                }
            })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '您取消了删除!',
            })
        })
}

onMounted(() => {
    BasicinfoShow();
    GoodsShow();
})

</script>


<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>